<?php


namespace app\home\controller;

use app\admin\model\Push;
use app\home\model\ApprovalDepartment;
use app\home\model\ApprovalLeave;
use app\home\model\ApprovalOvertime;
use app\home\model\ApprovalPurchase;
use app\home\model\ApprovalPurchaseDetail;
use app\home\model\ApprovalSeal;
use app\home\model\ApprovalUser;
use app\home\model\WechatDepartment;
use app\home\model\WechatDepartmentUser;
use app\home\model\WechatUser;
use app\home\model\WechatUserTag;
use com\wechat\TPQYWechat;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 在线审批
 * Class Approval
 * @package app\home\controller
 */
class Approval extends Base
{
    protected $userid = "";
    protected $permission = "";
    public function _initialize()
    {
        parent::_initialize();
        $this->anonymous();
        $this->jssdk();
        //判断用户状态
        $this->userid = session('userId');
        $res = WechatUserTag::where(['userid' => $this->userid])->find();
        if($res) {
            switch ($res['tagid']) {
                case 1: //总经理
                    $permission = 1;
                    break;
                case 2: //副总
                    $permission = 2;
                    break;
                case 3: //科室长
                    $permission = 3;
                    break;
                default: //普通员工
                    $permission = 4;
                    break;
            }
        }else {
            $permission = 4;
        }
        $this->permission = $permission;
    }

    /**
     *  在线审批首页
     *  query_type 0 => "全部", 1 => "请假审批", 2 => "公章使用审批", 3 => "物资采购审批", 4 => "部门联系单", 5 => "加班申请审批"
     *  status 申请 '' => 全部，0 => 待审批，1 =》 已通过，2=〉已拒绝，3=》进行中
                审批  '' =〉全部，0=》待审批，1 =〉 已通过，2=》已拒绝
     */
    public function index () {
        $Model = new ApprovalUser();
        $query_time = input('query_time',''); //查询时间
        $query_type = input('query_type',0); //查询类型
        $search = input('search'); //模糊搜索
        $query_status = input('status',''); //查询状态
        $type = input('type'); //类型，2申请，3审批
        $length = input('length',0);
        if(IS_POST) {
            $list = $Model->getList($type,$this->userid,$length,$query_type,$query_status,$query_time,$search);
            if($list) {
                return $this->success("加载成功","",$list);
            }else {
                return $this->error("无更多数据");
            }
        }else {
            $list = [
                'permission' => $this->permission, //3科室长，内购唯一
                'apply' => $Model->getList(2,$this->userid,$length,$query_type,$query_status,$query_time,$search),
                'approval' => $Model->getList(3,$this->userid,$length,$query_type,$query_status,$query_time,$search)
            ];
            $this->assign('list',json_encode($list));
            $query_type_list = [ 0 => "全部", 1 => "请假审批", 2 => "公章使用审批", 3 => "物资采购审批", 4 => "部门联系单", 5 => "加班申请审批" ];
            $this->assign('queryTypeList',json_encode($query_type_list));
        }
        return $this->fetch();
    }

    /**
     *  新建请假审批
     */
    public function dayoff() {
        //更新审批权限
        $tags = WechatUserTag::where(['userid' => $this->userid])->select();
        if($tags) {
            foreach ($tags as $value) {
                switch ($value['tagid']) {
                    case 3:
                        $permission = 3; //多标签科室长权限优先
                        break;
                    default:
                        $permission = $this->permission;
                        break;
                }
            }
        }else {
            $permission = $this->permission;
        }
        //departmentid 5 办公室，18财务科
        if($permission == 4) {
            $department = WechatDepartmentUser::where(['userid' => $this->userid])->find();
            $depart = [5,6,14,26,31];
            if(in_array($department['departmentid'],$depart)) {
                $permission = 5; //办公室成员
            } elseif ($department['departmentid'] == 18) {
                $permission = 6; //财务科成员
            }
        }
        if(IS_POST) {
            $post = input('post.');
            if($post) {
                $data = [
                    'class' => 1,
                    'start_time' => $post['start_time'],
                    'end_time' => $post['end_time'],
                    'duration' => $post['duration'],
                    'type' => $post['type'],
                    'agent' => $post['agent'],
                    'content' => $post['content'],
                    'apply_user' => $this->userid,
                ];
                $res = ApprovalLeave::create($data);
                if($res) {
                    $user = $this->setDayoffUsers($post,$res,$permission);
                    //创建审批用户
                    foreach ($user as $create) {
                        $person = WechatUser::where(['userid' => $create['approval_user']])->find();
                        $create['username'] = $person['name'];
                        ApprovalUser::create($create);
                    }
                    //发送审批消息
                    $this->setPushData(1,1,$user[0]['approval_user'],$res);

                    $this->success("申请成功",Url('Approval/index'));
                }else {
                    $this->error("申请失败");
                }
            }else {
                return $this->error("提交失败,数据不能为空");
            }
        }else {
            $approval_user = $this->getDayoffApprovalUser($permission);
            $this->assign('approval_user',json_encode($approval_user));
            $this->assign('permission',$permission);
            return $this->fetch();
        }
    }

    /**
     *  新建公章使用审批
     */
    public function officialseal() {
        $permission = $this->permission;
        if(IS_POST) {
            $post = input('post.');
            if($post) {
                $data = [
                    'class' => 2,
                    'title' => $post['title'],
                    'apply_user' => $post['apply_user'],
                    'apply_department' => $post['apply_department'],
                    'to_company' => $post['to_company'],
                    'content' => $post['content'],
                ];
                //v2.0上传图片
                if(isset($post['images'])) {
                    $data['images'] = $post['images'] ? json_encode($post['images']) : "";
                }
                $res = ApprovalSeal::create($data);
                if($res) {
                    $user = [];
                    //是否科室长
                    if($permission == 3) {
                        $user[0] = [
                            'class' => $res['class'],
                            'pid' => $res['id'],
                            'level' => 1,
                            'approval_user' => $this->userid,
                            'status' => 0
                        ];
                        $user[1] = [
                            'class' => $res['class'],
                            'pid' => $res['id'],
                            'level' => 2,
                            'approval_user' => $post['approval_user'],
                            'status' => -1
                        ];
                        $i = 2;
                    }else {
                        $user[0] = [
                            'class' => $res['class'],
                            'pid' => $res['id'],
                            'level' => 1,
                            'approval_user' => $post['approval_user'],
                            'status' => 0
                        ];
                        //获取副总
                        $tagUser = WechatUserTag::where(['tagid' => 2])->select();
                        foreach ($tagUser as $key => $value) {
                            $user[$key+1] = [
                                'class' => $res['class'],
                                'pid' => $res['id'],
                                'level' => 2,
                                'approval_user' => $value['userid'],
                                'status' => -1
                            ];
                        }
                        $i = $key + 2;
                    }
                    $lead = WechatUserTag::where(['tagid' => 1])->find();
                    $user[$i] = [
                        'class' => $res['class'],
                        'pid' => $res['id'],
                        'level' => 3,
                        'approval_user' => $lead['userid'],
                        'status' => -1
                    ];
                    //创建审批用户
                    foreach ($user as $create) {
                        $person = WechatUser::where(['userid' => $create['approval_user']])->find();
                        $create['username'] = $person['name'];
                        ApprovalUser::create($create);
                    }
                    //发送审批消息
                    $this->setPushData(1,2,$user[0]['approval_user'],$res);

                    $this->success("申请成功",Url('Approval/index'));
                }else {
                    $this->error("申请失败");
                }
            }else {
                return $this->error("提交失败,数据不能为空");
            }
        }else {
            $apply_user = $this->getApplyUser($this->userid);
            $this->assign('apply_user',json_encode($apply_user));
            $approval_user = $this->getApprovalUser($permission);
            $this->assign('approval_user',json_encode($approval_user));

            return $this->fetch();
        }
    }

    /**
     *  新建物资采购审批
     */
    public function purchase() {
        $permission = $this->permission;
        if(IS_POST) {
            $post = input('post.');
            if($post) {
                $data = [
                    'class' => 3,
                    'title' => $post['title'],
                    'apply_user' => $post['apply_user'],
                    'apply_department' => $post['apply_department'],
                    'apply_time' => $post['apply_time'],
                ];
                $detail = $post['data'];
                unset($post['data']);
                $res = ApprovalPurchase::create($data);
                if($res) {
                    //创建申请采购内容
                    foreach ($detail as $key =>$value) {
                        $value['pid'] = $res['id'];
                        ApprovalPurchaseDetail::create($value);
                    }
                    $user[0] = [
                        'class' => $res['class'],
                        'pid' => $res['id'],
                        'level' => 1,
                        'approval_user' => $post['approval_user'],
                        'status' => 0
                    ];
                    $tagUser = WechatUserTag::where(['tagid' => 1])->select();
                    foreach ($tagUser as $k => $v) {
                        $user[$k+1] = [
                            'class' => $res['class'],
                            'pid' => $res['id'],
                            'level' => 2,
                            'approval_user' => $v['userid'],
                            'status' => -1
                        ];
                    }
                    foreach ($user as $create) {
                        $person = WechatUser::where(['userid' => $create['approval_user']])->find();
                        $create['username'] = $person['name'];
                        ApprovalUser::create($create);
                    }
                    //发送审批消息
                    $this->setPushData(1,3,$post['approval_user'],$res);

                    $this->success("申请成功",Url('Approval/index'));
                }else {
                    $this->error("申请失败");
                }
            }else {
                return $this->error("提交失败,数据不能为空");
            }
        }else {
           if($permission == 3) {
               $apply_user = $this->getApplyUser($this->userid);
               $this->assign('apply_user',json_encode($apply_user));
               $approval_user = $this->getApprovalUser($permission);
               $this->assign('approval_user',json_encode($approval_user));
               return $this->fetch();
           }else {
               return $this->error("无权限创建该审批申请",Url('Approval/index'));
           }
        }
    }

    /**
     *  新建部门联系单审批
     */
    public function department() {
        if(IS_POST) {
            $post = input('post.');
            if($post) {
                $data = [
                    'class' => 4,
                    'title' => $post['title'],
                    'assign_department' => $post['assign_department'],
                    'handle_department' => $post['handle_department'],
                    'assign_time' => $post['assign_time'],
                    'plan_time' => $post['plan_time'],
                    'content' => $post['content'],
                    'apply_user' => $this->userid,
                ];
                //v2.0上传图片
                if(isset($post['images'])) {
                    $data['images'] = $post['images'] ? json_encode($post['images']) : "";
                }
                $res = ApprovalDepartment::create($data);
                if($res) {
                    //创建审批用户
                    $user = [
                        0 => [
                            'class' => $res['class'],
                            'pid' => $res['id'],
                            'level' => 1,
                            'approval_user' => $post['approval_user1'],
                            'status' => 0
                        ],
                        1 => [
                            'class' => $res['class'],
                            'pid' => $res['id'],
                            'level' => 2,
                            'approval_user' => $post['approval_user2'],
                            'status' => -1
                        ],
                        2 => [
                            'class' => $res['class'],
                            'pid' => $res['id'],
                            'level' => 3,
                            'approval_user' => $post['approval_user3'],
                            'status' => -1
                        ],
                    ];
                    foreach ($user as $create) {
                        $person = WechatUser::where(['userid' => $create['approval_user']])->find();
                        $create['username'] = $person['name'];
                        ApprovalUser::create($create);
                    }
                    //发送审批消息
                    $this->setPushData(1,4,$user[0]['approval_user'],$res);

                    $this->success("申请成功",Url('Approval/index'));
                }else {
                    $this->error("申请失败");
                }
            }else {
                return $this->error("提交失败,数据不能为空");
            }
        }else {
            $department = $this->getDepartment();
            $this->assign('department',json_encode($department));
            $approval_user = $this->getApprovalUser(3); //科室长权限
            $this->assign('approval_user',json_encode($approval_user));

            return $this->fetch();
        }
    }

    /**
     * 加班申请审批class5
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function overtime() {
        $permission = $this->permission;
        if(IS_POST) {
            $post = input('post.');
            if($post) {
                $data = [
                    'class' => 5,
                    'type' => $post['type'],
                    'start_time' => $post['start_time'],
                    'end_time' => $post['end_time'],
                    'duration' => $post['duration'],
                    'content' => $post['content'],
                    'apply_user' => $this->userid,
                ];
                $res = ApprovalOvertime::create($data);
                if($res) {
                    $user[0] = [
                        'class' => $res['class'],
                        'pid' => $res['id'],
                        'level' => 1,
                        'approval_user' => $post['approval_user'],
                        'status' => 0
                    ];
                    foreach ($user as $create) {
                        $person = WechatUser::where(['userid' => $create['approval_user']])->find();
                        $create['username'] = $person['name'];
                        ApprovalUser::create($create);
                    }
                    //发送审批消息
                    $this->setPushData(1,5,$post['approval_user'],$res);

                    $this->success("申请成功",Url('Approval/index'));
                }else {
                    $this->error("申请失败");
                }
            }else {
                return $this->error("提交失败,数据不能为空");
            }
        }else {
            $apply_user = $this->getApplyUser($this->userid);
            $this->assign('apply_user',json_encode($apply_user));
            $approval_user = $this->getApprovalUser($permission);
            $this->assign('approval_user',json_encode($approval_user));

            return $this->fetch();
        }
    }

    public function getOvertimeApprovalUser() {
        $permission = $this->permission;
        $type = input('type',1); //1普通 //2应急
        switch ($permission) {
            case 3:
                //新增办公司、财务直接由总经理审批
                $map = [
                    'userid' => $this->userid,
                    'tagid' => ["in",[5,6]]
                ];
                $other = WechatUserTag::where($map)->find();
                if($other) {
                    $user = WechatUserTag::where(['tagid' => 1])->select();
                }else {
                    $user = WechatUserTag::where(['tagid' => 2])->select();
                }
                break;
            default:
                if($type == 1) {
                    $user = WechatUserTag::where(['tagid' => 3])->select();
                }else {
                    $user = WechatUserTag::where(['tagid' => 2])->select();
                }
                break;
        }
        foreach ($user as $value) {
            $u = WechatUser::where(['userid' => $value['userid']])->find();
            $value['username'] = $u['name'];
        }
        if($user) {
            return $this->success("获取成功","",$user);
        }else {
            return $this->error("获取失败");
        }
    }


    /**
     * 修改
     */
    public function getDetail() {
        $id = input('id');
        $class = input('class');
        $setTable = $this->setTables($class);
        $detail = Db::table($setTable['table'])->where(['id' => $id])->find();
        if($class == 1 || $class == 5) {
            $detail['type_text'] = $setTable['type'][$detail['type']];
        }
        if($class == 3) {
            $detail['purchase_content'] = Db::table($setTable['table_detail'])->where(['pid' => $detail['id']])->select();
        }
        if($class == 4) {
            $department1 = WechatDepartment::get($detail['assign_department']);
            $detail['assign_department_name'] = $department1['name'];
            $department2 = WechatDepartment::get($detail['handle_department']);
            $detail['handle_department_name'] = $department2['name'];
        }
        if($class == 2 || $class == 4) {
            $detail['images'] = $detail['images'] ? json_decode($detail['images']) : [];
        }
        $map = [
            'class' => $class,
            'pid' => $id
        ];
        $detail['approval_user'] = Db::table('zm_approval_user')->where($map)->select();
        if($detail) {
            return $this->success("获取成功","",$detail);
        }else {
            return $this->error("获取失败");
        }
    }

    /**
     * 修改 class:1请假，2公章，3采购，4部门联系
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit() {
        $data = input('post.');
        $content = $data['content'];
        $content['status'] = 0;
        $content['reason'] = null;
        if(isset($content['images'])) {
            $content['images'] = json_encode($content['images']);
        }
        $approval_user = $data['approval_user'];
        if(is_array($approval_user)) {
            $send_user = $approval_user[0]['approval_user'];
        }else {
            $send_user = $approval_user;
        }
        if($content && $approval_user) {
            $setTable = $this->setTables($content['class']);
            if($content['class'] == 1) {
                $res1 = model($setTable['model'])->where(['id' => $content['id']])->update($content);

                $map = [
                    'class' => $content['class'],
                    'pid' => $content['id']
                ];
                ApprovalUser::where($map)->delete();
                $post = [
                    'duration' => $content['duration'],
                    'approval_user' => $data['approval_user']
                ];
                $res = [
                    'id' => $content['id'],
                    'class' => $content['class']
                ];
                $user = $this->setDayoffUsers($post,$res, $data['permission']);
                foreach ($user as $create) {
                    $person = WechatUser::where(['userid' => $create['approval_user']])->find();
                    $create['username'] = $person['name'];
                    $res = ApprovalUser::create($create);
                }
                if($res) {
                    $res2 = 1;
                }else {
                    $res2 = 0;
                }
            }elseif($content['class'] == 3) {
                $purchase_content = $content['data'];
                unset($content['data']);
                $res1 = model($setTable['model'])->where(['id' => $content['id']])->update($content);
                if($res1) {
                    model($setTable['model_detail'])->where(['pid' => $content['id']])->delete();
                    foreach ($purchase_content as $value) {
                        $value['pid'] = $content['id'];
                        unset($value['id']);
                        model($setTable['model_detail'])->create($value);
                    }
                }
                foreach ($approval_user as $value) {
                    //重置状态
                    if($value['level'] == 1) {
                        $value['status'] = 0;
                    }else if($value['level'] == 2) {
                        $value['status'] = -1;
                    }else {
                        $value['status'] = -1;
                    }
                    if(empty($value['approval_time'])) {
                        $value['approval_time'] = null;
                    }
                    $info = ApprovalUser::where(['id' => $value['id']])->update($value);
                    if($info == 1) {
                        $res2 = 1;
                    }else {
                        $res2 = 0;
                    }
                }
            }else if($content['class'] == 5){
                $res1 = model($setTable['model'])->where(['id' => $content['id']])->update($content);
                $map = [
                    'class' => $content['class'],
                    'pid' => $content['id']
                ];
                ApprovalUser::where($map)->delete();
                $create = [
                    'class' => 5,
                    'pid' => $content['id'],
                    'approval_user' => $data['approval_user'],
                    'status' => 0
                ];
                $person = WechatUser::where(['userid' => $data['approval_user']])->find();
                $create['username'] = $person['name'];
                $info = ApprovalUser::create($create);
                if($info) {
                    $res2 = 1;
                }else {
                    $res2 = 0;
                }
            }else {
                $res1 = model($setTable['model'])->where(['id' => $content['id']])->update($content);
                foreach ($approval_user as $value) {
                    //重置状态
                    if($value['level'] == 1) {
                        $value['status'] = 0;
                    }else if($value['level'] == 2) {
                        $value['status'] = -1;
                    }else {
                        $value['status'] = -1;
                    }
                    if(empty($value['approval_time'])) {
                        $value['approval_time'] = null;
                    }
                    $info = ApprovalUser::where(['id' => $value['id']])->update($value);
                    if($info == 1) {
                        $res2 = 1;
                    }else {
                        $res2 = 0;
                    }
                }
            }
            if($res1 == 1 || $res2 == 1) {
                $this->setPushData(1,$content['class'],$send_user,$content);
                $this->success("修改成功");
            }else {
                $this->error("未修改任何内容,提交失败");
            }
        }

    }

    /**
     * 删除
     */
    public function del() {
        $id = input('id');
        $class = input('class');
        $setTable = $this->setTables($class);
        $res = Db::table($setTable['table'])->where(['id' => $id])->delete();
        if($res) {
            $map = [
                'pid' => $id,
                'class' => $class
            ];
            ApprovalUser::where($map)->delete();
            $this->success("删除成功");
        }else {
            $this->error("删除失败");
        }
    }

    /**
     * 请假审批详情class=1
     * 公章使用审批详情class=2
     * 资采购审批详情class=3
     * 部门联系单审批详情class=4
     */
    public function detail() {
        $approvalUserModel = new ApprovalUser();
        $id = input('id');
        $class = input('class');
        $setTable = $this->setTables($class);
        if(IS_POST) {
            $status = input('status'); //1审核通过，2不通过
            $total_level = input('total_level');
            $map = [
                'class' => $class,
                'pid' => $id,
                'approval_user' => $this->userid,
            ];
            $res = $approvalUserModel->where($map)->find();
            if($status == 1) {
                //更改审批用户状态
                $data = [
                    'approval_time' => time(),
                    'status' => 1
                ];
                $info = $approvalUserModel->where(['id' => $res['id']])->update($data);
                if($total_level == $res['level']) {
                    //是否是最后一级审批用户,更改申请状态为审批通过
                    Db::table($setTable['table'])->where(['id' => $res['pid']])->update(['status' => 1]);
                    //发送审批
                    $msg = Db::table($setTable['table'])->where(['id' => $res['pid']])->find();
                    $this->setPushData(2,$msg['class'],$msg['apply_user'],$msg);
                } else {
                    //更改申请状态为进行中
                    Db::table($setTable['table'])->where(['id' => $res['pid']])->update(['status' => 3]);
                    //激活下一级审批用户为待审批
                    $map_next = [
                        'class' => $class,
                        'pid' => $id,
                        'level' => ($res['level'] + 1)
                    ];
                    $approvalUserModel->where($map_next)->update(['status' => 0]);
                    //发送审批消息
                    $push_data = $approvalUserModel->where($map_next)->select();
                    foreach ($push_data as $push) {
                        $this->setPushData(1,$push['class'],$push['approval_user'],['id' => $push['pid']]);
                    }
                }
            }else {
                $reason = input('reason');
                //更改审批及申请状态不通过
                $data = [
                    'approval_time' => time(),
                    'status' => 2
                ];
                $info = $approvalUserModel->where(['id' => $res['id']])->update($data);
                Db::table($setTable['table'])->where(['id' => $res['pid']])->update(['reason' => $reason,'status' => 2]);
                //发送审批
                $msg = Db::table($setTable['table'])->where(['id' => $res['pid']])->find();
                $this->setPushData(2,$msg['class'],$msg['apply_user'],$msg);
            }
            //审批操作完成后进行
            $result =  Db::table($setTable['table'])->where(['id' => $id])->find();
            if(in_array($result['status'],[1,2]) && $result['class'] != 4) {
                $user1 = WechatUserTag::where(['tagid' => 5])->field('userid')->select();
                if($result['class'] == 3) {
                    $user2 = WechatDepartmentUser::where(['departmentid' => 31])->field('userid')->select();
                }else {
                    $user2 = [];
                }
                $users = array_merge($user1,$user2);
                foreach ($users as $user) {
                    $this->setPushData(3,$result['class'],$user['userid'],$result);
                }
            }
            if($info) {
                //更改其他用户状态
                $map_status = [
                    'class' => $class,
                    'pid' => $id,
                    'level' => $res['level'],
                    'approval_user' => ['neq',$this->userid],
                ];
                $approvalUserModel->where($map_status)->update(['status' => -1]);
                return $this->success("审批成功","",$result);
            }else {
                return $this->error("审批失败");
            }
        }else {
            //获取对应申请信息
            $detail = Db::table($setTable['table'])->where(['id' => $id])->find();
            //获取用户部门及其他信息
            $person = WechatUser::where(['userid' => $detail['apply_user']])->find();
            $depart = WechatDepartment::get($person['department']);
            $detail['header'] = $person['header'] ? $person['header'] : $person['avatar'];
            $detail['username'] = $person['name'];
            $detail['department'] = $depart['name'];
            $detail['class_text'] = $setTable['class_text'];
            if($class == 1 || $class == 5) {
                $detail['type_text'] = $setTable['type'][$detail['type']];
            }
            if($class == 3) {
                $detail['purchase_content'] = Db::table($setTable['table_detail'])->where(['pid' => $detail['id']])->select();
            }
            if($class == 4) {
                $department1 = WechatDepartment::get($detail['assign_department']);
                $detail['assign_department_name'] = $department1['name'];
                $department2 = WechatDepartment::get($detail['handle_department']);
                $detail['handle_department_name'] = $department2['name'];
            }

            if($class == 2 || $class == 4) {
                if($class == 2 || $class == 4) {
                    $detail['index_path'] = [];
                    $detail['preview_path'] = [];
                    if($detail['images']) {
                        $detail['images'] = json_decode($detail['images']);
                        foreach ($detail['images'] as $value) {
                            $detail['index_path'][] = thumb($value);
                            $detail['preview_path'][] = thumb($value,1200,720);
                        }
                    }else{
                        $detail['images'] = [];
                    }
                }
            }
            //获取审批人信息
            $map = [
                'class' => $class,
                'pid' => $id
            ];
            $user = Db::table("zm_approval_user")->where($map)->order('approval_time desc,status desc')->select();
            if($user) {
                foreach ($user as $key => $value) {
                    $detail['user'][$value['level']][] = $value;
                }
            }else {
                $detail['user'] = [];
            }
            $detail['total_level'] = count($detail['user']);
            //判断是否审核
            $map_user = [
                'class' => $class,
                'pid' => $id,
                'approval_user' => $this->userid,
                'status' => 0
            ];
            $is_approval = $approvalUserModel->where($map_user)->find();
            if($is_approval) {
                $detail['is_approval'] = 1; //可以执行审核
            }else {
                $detail['is_approval'] = 0; //不可操作
            }
            $this->assign('title',$detail['class_text']);
            $this->assign('detail',json_encode($detail));
            $this->assign('userid',$this->userid);
            return $this->fetch();
        }
    }

    /**
     * 部门联系单确认回调
     * $type 1 转发，2确认
     * forwarding_time 三级审批用户转发时间
     * completion_time 一级审批用户确认时间
     */
    public function setDepartmentStatus() {
        $type = input('type');
        if($type == 1) {
            $data['forwarding_time'] = time();
        }else {
            $data['completion_time'] = time();
        }
        $id = input('id');
        $res = ApprovalDepartment::where(['id' => $id])->update($data);
        if($res) {
            return $this->success("操作成功","",$res);
        }else {
            return $this->error("操作失败");
        }
    }

    /**
     * 获取对应表格及信息
     */
    private function setTables($class) {
        switch ($class) {
            case 1:
                $table = "zm_approval_leave";
                $model = "approval_leave";
                $model_detail = "";
                $class_text = "请假审批";
                $type = [1 => "事假", 2 => "护理假", 3 => "病假", 4 => "丧假", 5 => "工伤假", 6 => "产假", 7 => "婚嫁假", 8 => "哺乳假",];
                $table_detail = "";
                break;
            case 2:
                $table = "zm_approval_seal";
                $model = "approval_seal";
                $model_detail = "";
                $class_text = "公章使用审批";
                $type = "";
                $table_detail = "";
                break;
            case 3:
                $table = "zm_approval_purchase";
                $table_detail = "zm_approval_purchase_detail";
                $model = "approval_purchase";
                $model_detail = "approval_purchase_detail";
                $class_text = "物资采购审批（内购）";
                $type = "";
                break;
            case 4:
                $table = "zm_approval_department";
                $model = "approval_department";
                $model_detail = "";
                $class_text = "部门联系单";
                $table_detail = "";
                $type = "";
                break;
            case 5:
                $table = "zm_approval_overtime";
                $model = "approval_overtime";
                $model_detail = "";
                $class_text = "加班申请审批";
                $type = [1 => "普通审批" , 2 => "应急审批"];
                $table_detail = "";
                break;
            default:
                return $this->error("无对应类别数据，请重新检查！");
                break;
        }
        $return = [
            'model' => $model,
            'model_detail' => $model_detail ? $model_detail : "",
            'table' => $table,
            'class_text' => $class_text,
            'type' => $type ? $type : "",
            'table_detail' => $table_detail ? $table_detail : "",
        ];
        return $return;
    }

    /**
     * 获取办理部门负责人
     */
    public function getDepartmentUser() {
        $deparmentid = input('id');
//        $user = WechatDepartmentUser::where(['departmentid' => $deparmentid])->select(); //隐藏普通用户
        $user = WechatUserTag::where(['tagid' => 3])->select(); //获取科室长
        if($user) {
            foreach ($user as $value) {
                $u = WechatUser::where(['userid' => $value['userid']])->find();
                $value['username'] = $u['name'];
            }
            return $this->success("获取成功","",$user);
        }else {
            return $this->error("获取失败,不存在部门负责人");
        }
    }

    /**
     * 获取请假审批审核人
     * $permission 不同用户权限
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getDayoffApprovalUser($permission) {
        switch ($permission) {
            case 3:
                //新增办公司、财务直接由总经理审批
                $map = [
                    'userid' => $this->userid,
                    'tagid' => ["in",[5,6]]
                ];
                $other = WechatUserTag::where($map)->find();
                if($other) {
                    $user = WechatUserTag::where(['tagid' => 1])->select();
                }else {
                    $user = WechatUserTag::where(['tagid' => 2])->select();
                }
                break;
            case 4:
                $user = WechatUserTag::where(['tagid' => 3])->select();
                break;
            case 5:
                $user = WechatUserTag::where(['tagid' => 5])->select();
                break;
            case 6:
                $user = WechatUserTag::where(['tagid' => 6])->select();
                break;
            default:
                $user = WechatUserTag::where(['tagid' => 3])->select();
                break;
        }
        foreach ($user as $value) {
            $u = WechatUser::where(['userid' => $value['userid']])->find();
            $value['username'] = $u['name'];
        }
        return $user;
    }

    /**
     * 设置请假审批用户层级
     * @param $post
     * @param $res
     * @param $permission
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setDayoffUsers($post,$res,$permission) {
        //新增办公司、财务直接由总经理审批
        $map = [
            'userid' => $this->userid,
            'tagid' => ["in",[5,6]]
        ];
        $other = WechatUserTag::where($map)->find();
        //根据天数判断审批人
        $day = $post['duration'];
        $user = [];
        if($day <= 1) { //1天以内科室长审批
            //科室长
            if($permission == 3) {
                $user[0] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 1,
                    'approval_user' => $this->userid,
                    'status' => 0
                ];
                $user[1] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 2,
                    'approval_user' => $post['approval_user'],
                    'status' => -1
                ];
            }else { // 其他
                $user[0] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 1,
                    'approval_user' => $post['approval_user'],
                    'status' => 0
                ];
            }
        }elseif ($day > 1 && $day < 3) { //1 ~ 3科室长由总经理，普通用户到副总
            if($permission == 3) {
                $user[0] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 1,
                    'approval_user' => $this->userid,
                    'status' => 0
                ];
                $user[1] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 2,
                    'approval_user' => $post['approval_user'],
                    'status' => -1
                ];
                if(empty($other)) { //如果不是办公室财务科科长，需要增加一级
                    $i = 2;
                    //获取总经理
                    $tagUser1 = WechatUserTag::where(['tagid' => 1])->select();
                    foreach ($tagUser1 as $k => $v) {
                        $user[$i] = [
                            'class' => $res['class'],
                            'pid' => $res['id'],
                            'level' => 3,
                            'approval_user' => $v['userid'],
                            'status' => -1
                        ];
                        $i = $i + $k + 1;
                    }
                }
            }else if($permission == 5 || $permission == 6){ //财务、办公室由科室长直接审批
                $user[0] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 1,
                    'approval_user' => $post['approval_user'],
                    'status' => 0
                ];
            }else {
                $user[0] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 1,
                    'approval_user' => $post['approval_user'],
                    'status' => 0
                ];
                //获取副总
                $tagUser = WechatUserTag::where(['tagid' => 2])->select();
                foreach ($tagUser as $key => $value) {
                    $user[$key+1] = [
                        'class' => $res['class'],
                        'pid' => $res['id'],
                        'level' => 2,
                        'approval_user' => $value['userid'],
                        'status' => -1
                    ];
                }
            }
        }elseif ($day >= 3) { //3及以上
            if($permission == 3) {
                $user[0] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 1,
                    'approval_user' => $this->userid,
                    'status' => 0
                ];
                $user[1] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 2,
                    'approval_user' => $post['approval_user'],
                    'status' => -1
                ];
                if(empty($other)) { //如果不是办公室财务科科长，需要增加一级
                    $i = 2;
                    //获取总经理
                    $tagUser1 = WechatUserTag::where(['tagid' => 1])->select();
                    foreach ($tagUser1 as $k => $v) {
                        $user[$i] = [
                            'class' => $res['class'],
                            'pid' => $res['id'],
                            'level' => 3,
                            'approval_user' => $v['userid'],
                            'status' => -1
                        ];
                        $i = $i + $k + 1;
                    }
                }
            }else if($permission == 5 || $permission == 6){
                $user[0] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 1,
                    'approval_user' => $post['approval_user'],
                    'status' => 0
                ];
                //获取总经理
                $tagUser1 = WechatUserTag::where(['tagid' => 1])->select();
                foreach ($tagUser1 as $k => $v) {
                    $user[$k+1] = [
                        'class' => $res['class'],
                        'pid' => $res['id'],
                        'level' => 2,
                        'approval_user' => $v['userid'],
                        'status' => -1
                    ];
                }
            }else {
                $user[0] = [
                    'class' => $res['class'],
                    'pid' => $res['id'],
                    'level' => 1,
                    'approval_user' => $post['approval_user'],
                    'status' => 0
                ];
                //获取副总
                $tagUser = WechatUserTag::where(['tagid' => 2])->select();
                foreach ($tagUser as $key => $value) {
                    $user[$key+1] = [
                        'class' => $res['class'],
                        'pid' => $res['id'],
                        'level' => 2,
                        'approval_user' => $value['userid'],
                        'status' => -1
                    ];
                }
                $i = $key + 2;
                //获取总经理
                $tagUser1 = WechatUserTag::where(['tagid' => 1])->select();
                foreach ($tagUser1 as $k => $v) {
                    $user[$i] = [
                        'class' => $res['class'],
                        'pid' => $res['id'],
                        'level' => 3,
                        'approval_user' => $v['userid'],
                        'status' => -1
                    ];
                    $i = $i + $k + 1;
                }
            }
        }
        return $user;
    }

    /**
     * 获取其他类型审批人信息
     * @param $permission
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getApprovalUser($permission) {
        //科室长获取副总，其它为普通用户获取科室长
        if($permission == 3) {
            $user = WechatUserTag::where(['tagid' => 2])->select();
        }else {
            $user = WechatUserTag::where(['tagid' => 3])->select();
        }
        foreach ($user as $value) {
            $u = WechatUser::where(['userid' => $value['userid']])->find();
            $value['username'] = $u['name'];
        }
        return $user;
    }

    /**
     * 获取申请人信息
     * @param $userId
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getApplyUser($userId) {
        $user = WechatUser::where(['userid' => $userId])->field('userid,name,department')->find();
        if($user) {
            $department = WechatDepartment::where(['id' => $user['department']])->find();
            $user['department_name'] = $department['name'];
        }
        return $user;
    }

    /**
     * 获取部门审批部门列表
     */
    public function getDepartment() {
        $depart = [];
        $depart1 = Db::query("select * from zm_wechat_department where parentid = 1 order by `order` desc");
        foreach ($depart1 as $k1 => $v1) {
            //获取存在用户部门
            $is_user1 = WechatDepartmentUser::where(['departmentid' => $v1['id']])->select();
            if($is_user1) {
                $depart[] = $v1;
            }
//            $depart2 = Db::query("select * from zm_wechat_department where parentid = ".$v1['id']." order by `order` desc");
//            foreach ($depart2 as $k2 => $v2) {
//                $is_user2 = WechatDepartmentUser::where(['departmentid' => $v2['id']])->select();
//                if($is_user2) {
//                    $depart[] = $v2;
//                }
//                $depart3 = Db::query("select * from zm_wechat_department where parentid = ".$v2['id']." order by `order` desc");
//                foreach ($depart3 as $v3) {
//                    $is_user3 = WechatDepartmentUser::where(['departmentid' => $v3['id']])->select();
//                    if($is_user3) {
//                        $depart[] = $v3;
//                    }
//                }
//            }
        }
        return $depart;
    }

    /**
     * 获取审批推送数据
     * $t 推送类型，1：审批 2：申请 ,3:审批完成推送
     * $class
     * $data
     */
    private function setPushData($t = 1,$class,$user,$data) {
        switch ($class) {
            case 1:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[请假审批]";
                break;
            case 2:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[公章使用审批]";
                break;
            case 3:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[物资采购审批]";
                break;
            case 4:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[部门联系单审批]";
                break;
            case 5:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[加班申请审批]";
                break;
            default:
                Log::write("审批消息推送失败，不存在对应类别审批");
                break;
        }

        $pushData = [
//            'userid' => $user,
            'userid' => "18768112486",
            'title' =>  $title,
            'description' => "<div class=\"gray\">时间: ".date("Y-m-d H:i",time())."</div><div class=\"gray\">类型:".$type_text."</div><div class=\"highlight\">点击查看</div>",
            'url' => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']."/home/approval/detail/type/".$type."/class/".$class."/id/".$data['id'],
        ];
        $this->push($pushData);


    }

    /**
     * 推送
     */
    private function push($data){
        $send = [
            "title" => $data['title'],
            "description" => $data['description'],
            "url" => $data['url'],
        ];
        //发送给服务号
        $Wechat = new TPQYWechat(Config::get('approval'));
        $message = array(
            "touser" => $data['userid'],
//            "totag" => toTag,
            "msgtype" => 'textcard',
            "agentid" => config('approval.agentid'),
            "textcard" => $send,
            "safe" => "0"
        );
        $data = [
            'type' => 1,
            'agentname' => "approval",
            'touser' => $message['touser'],
            'msgtype' => $message['msgtype'],
            'agentid' => $message['agentid'],
            'sendcontent' => json_encode($message['textcard']),
            'safe' => $message['safe'],
        ];
        $res = Push::create($data);
        try {
            $msg = $Wechat->sendMessage($message);
            if ($msg['errcode'] == 0){
                Push::where('id',$res['id'])->update(['status' => 1,'update_time' => time()]);
                Log::write("审批消息发送：发送成功");
            }else{
                Log::write("审批消息发送：发送失败");
            }
            Log::write($msg);
        }catch (Exception $exception) {
            $msg = $exception->getMessage();
            Log::write("消息发送崩溃：发送失败".$msg);
        }
    }
}
